var React = require('react');
var _ = require('underscore');
require('./select.scss');
var Select = React.createClass({
  displayName: 'select',
  propTypes: {
    title: React.PropTypes.string,
    onSelect: React.PropTypes.func,
    data: React.PropTypes.any,
    autoFocus: React.PropTypes.any,
    operation: React.PropTypes.any,
    nameKey: React.PropTypes.string,
  },
  getInitialState() {
    return {
      data: this.props.data,
      keyWord: null,
      isSearch:false,
      isOperation:false,
      searchResult:[]
    }
  },
  componentWillUpdate(nextProps) {
    //console.log(nextProps.data,"componentWillUpdate");
    if (this.state.data != nextProps.data && !this.state.isSearch) {
      this.setState({
        data:  nextProps.data
      });
    }
  },
  componentDidMount() {
    var { autoFocus, operation } = this.props;
    if (autoFocus) {
      this.refs.filter_input.focus();
    }
    if(operation){
      this.setState({
        isOperation: true
      });
    }
  },
  handleClick(event, selectedItem) {
    if (this.props.onSelect) {
      this.props.onSelect(selectedItem);
    }
    var data = this.state.data;
    _.each(data, (item) => {
      item.active = false;
    });
    var willActiveItem = _.find(data, item => item.id == selectedItem.id);
    willActiveItem.active = true;
    this.setState({
      data,
      isSearch:false,
      keyWord:""
    });
  },
  handleInputChange(event) {

    var {data} = this.props;
    var value = event.target.value;
    data.map(function(item){
      item.active = false;
    });
    var searchResult = [];
    for(var i in data){
      if(data[i].name.indexOf(value) != -1){
        searchResult.push(data[i]);
      }
    }
    if(!searchResult.length || value==null || value == ""){
      searchResult = this.props.data;
    }
    this.setState({
      keyWord: event.target.value,
      data:searchResult,
      isSearch:true
    });
  },
  handleKeyUp(event){
    this.handleInputChange(event);
  },
  handleKeyDown(event) {

  },
  handleSelectClick() {
    this.refs.filter_input.focus();
  },
  getWillActiveIndex(action) {
    var { data } = this.state;
    var willActiveIndex = -1;
    var currentActiveIndex = _.findIndex(data, {active: true});
    var lastIndex = 0;
    if (data && data.length >= 1) {
      lastIndex = data.length - 1;
    }
    if (currentActiveIndex < 0 || lastIndex == 0) {
      willActiveIndex = 0;
      return willActiveIndex;
    }
    if (action === 'up') {
      if (currentActiveIndex === 0) {
        willActiveIndex = lastIndex;
        return willActiveIndex;
      }
      willActiveIndex = currentActiveIndex - 1;
      return willActiveIndex;
    }
    if (action === 'down') {
      if (currentActiveIndex === lastIndex) {
        willActiveIndex = 0;
        return willActiveIndex;
      }
      willActiveIndex = currentActiveIndex + 1;
      return willActiveIndex;
    }
  },
  changeActive(action) {
    var { data } = this.state;
    var index = this.getWillActiveIndex(action);
    var currentActiveIndex = _.findIndex(data, {active: true});
    if (currentActiveIndex >= 0) {
      data[currentActiveIndex].active = false;
    }
    data[index].active = true;
    this.setState({
      data
    });
  },
  handleEdit(index,id,e) {
    e.stopPropagation();

    var { data } = this.state;
    data[index].isEdit = true;
    data[index].editName = data[index].name;
    this.setState({
      data
    });
  },
  handleDelete(index,id,e) {
    e.stopPropagation();

    var { data } = this.state;
    this.props.onDelete(id);
  },
  handleChangeItem(index,id,e) {
    e.stopPropagation();

    var { data } = this.state;
    data[index].editName = e.target.value;
    this.setState({
      data
    });
  },
  handleInputClick(e) {
    e.stopPropagation();
  },
  handleAmend(index,id,e) {
    e.stopPropagation();

    var { data } = this.state;
    var value = $(e.target).prev().val()
    data[index].isEdit = false;
    this.props.onEdit(index,id,value);
    this.setState({
      data
    });
  },
  render() {
    var { title, nameKey } = this.props;
    var { data, isOperation } = this.state;
    return (<div className="mod-select" onClick={this.handleSelectClick}>
      <h6>{title}</h6>
      <div className="input-wrapper-select">
        <div className="inner">
          <i className="iconfont icon-sousuo"></i>
          <input
            ref="filter_input" type="text" value={this.state.keyWord} placeholder="搜索关键字"
            onChange={this.handleInputChange} onKeyDown={this.handleKeyDown} onKeyUp={this.handleKeyUp}
          />
        </div>
      </div>
      <ul className="opt-wrapper">
        {data.map((item,index)=> {
          return <li
            key={item.id} className={item.active ? 'active' : null}
            onClick={(event) => {this.handleClick(event, item)}}>
            { nameKey ? item[nameKey] : item.name }
            {
                !!item.isEdit && isOperation ? <span className="edit-item">
                  <input type="text" value={nameKey ? item[nameKey] : item.editName} onClick={this.handleInputClick} onChange={this.handleChangeItem.bind(this,index,item.id)}/><
                    button type="button" className="button export" onClick={this.handleAmend.bind(this,index,item.id)}>修改</button>
                </span> : null
            }
            {
              !item.isEdit && isOperation ? <span className="operation">
                <a className="edit paging" href="javascript:void(0);" onClick={this.handleEdit.bind(this,index,item.id)}>
                  <em className="iconfont icon-bianji"></em>
                </a>
                <a className="delete paging" href="javascript:void(0);" onClick={this.handleDelete.bind(this,index,item.id)}>
                  <em className="iconfont icon-delete"></em>
                </a>
              </span> : null
            }
          </li>
        })}
      </ul>
    </div>);
  },
});

module.exports = Select;